package com.github.hongkaiwen.rxjava.play.problem1.play;


import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class FuturePlay {

    public static void main(String... args) throws ExecutionException, InterruptedException {
        //调用b，基于b的结果，做一点事情，然后去做别的事情
        ExecutorService service = Executors.newCachedThreadPool();

        //do by java
        Future<Integer> f2 = service.submit(() -> d());
        System.out.println("java do other things");
        System.out.println(f2.get());

        //do by callback
        service.execute(() -> f(result -> System.out.println(result)));
        System.out.println("callback do other things");

        //do by rx java
        Future<Integer> f1 = service.submit(() -> d());
        Observable.fromFuture(f1).subscribeOn(Schedulers.computation()).subscribe(System.out::println);
        //do other things
        System.out.println("rx do other things");


    }

    private static int d() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return 2;
    }

    private static void f(CallBack callBack){
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        callBack.handle(2);
    }
}

interface CallBack{
    void handle(int result);
}
